登录 白背景

leetcode/1-100/59. 螺旋矩阵 II.md

func generateMatrix(n int) [][]int {
    x := 0
    y := 0
    ret := make([][]int, n)
    for i := 0; i < n; i++ {
        ret[i] = make([]int, n)
    }
    ret[0][0] = 1
    edgeTop := 0
    edgeLeft := -1
    edgeRight := n
    edgeBottom := n
    now := 6 //2 4 8 6
    count := 1
    for {
        count++
        if now == 6 {
            if x+1 < edgeRight {
                x++
                ret[y][x] = count
                continue
            }
            edgeRight--
            if y+1 < edgeBottom {
                y++
                ret[y][x] = count
                now = 2
                continue
            }
            break
        }
        if now == 2 {
            if y+1 < edgeBottom {
                y++
                ret[y][x] = count
                continue
            }
            edgeBottom--
            if x-1 > edgeLeft {
                x--
                ret[y][x] = count
                now = 4
                continue
            }
            break
        }
        if now == 4 {
            if x-1 > edgeLeft {
                x--
                ret[y][x] = count
                continue
            }
            edgeLeft++
            if y-1 > edgeTop {
                y--
                ret[y][x] = count
                now = 8
                continue
            }
            break
        }
        if now == 8 {
            if y-1 > edgeTop {
                y--
                ret[y][x] = count
                continue
            }
            edgeTop++
            if x+1 < edgeRight {
                x++
                ret[y][x] = count
                now = 6
                continue
            }
            break
        }
    }
    return ret
}